import java.util.*;

class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        int r = binarySearch(arr, x);
        int l = r - 1;

        while(k-- > 0){
            if(l < 0){
                r++;
            }else if(r >= arr.length){
                l--;
            }else if(x - arr[l] <= arr[r] - x){
                l--;
            }else{
                r++;
            }
        }

        List<Integer> ans = new ArrayList<>();
        for(int i = l + 1; i < r; i++){
            ans.add(arr[i]);
        }
        return ans;
    }

    public int binarySearch(int[] arr, int x){
        int low = 0, high = arr.length;
        while(low < high){
            int mid = low + (high - low) / 2;
            if(arr[mid] < x){
                low = mid + 1;
            }else{
                high = mid;
            }
        }
        return low;
    }
}